<template>
  <div class="swiper-container" ref="swiper">
    <div class="swiper-wrapper">
      <slot></slot>
    </div>
    <!-- 如果需要分页器 -->
    <div v-if="isdos" class="swiper-pagination"></div>
    <div v-if="btn" style="background-size: 12px 44px;" class="swiper-button-next swiper-button-black"></div>
    <!-- 白色 -->
    <div v-if="btn" style="background-size: 12px 44px;" class="swiper-button-prev swiper-button-black"></div>
    <!-- 黑色 -->
  </div>
</template>

<script type="text/ecmascript-6">
  import Swiper from 'swiper'

  export default {
    name:'slider',
    props: {
      isdos:{
        type: Boolean,
        default: false
      } ,
      autoplay:{
        type: Boolean,
        default: false
      } ,
      active_index:{
        type: [Number,String],
        default: -1
      } ,
      btn:{
        type: Boolean,
        default:false
      },
      initialSlide:{
        type: Number,
        default: 0
      },
      sliderLength:{
        type: Number,
        default: 0
      }
    },
    created(){
      if(this.sliderLength){
        this.$watch('sliderLength',function (newL) {
          this.$nextTick(function () {
            setTimeout(()=>{
              this.swiper.onResize()
            },30)
          })
        })
      }
    },
    mounted() {
      setTimeout(()=>{
        this.initSwiper()
      },20)
    },
    activated(){
      if(this.autoplay){
        this.swiper.onResize()
        this.swiper.startAutoplay()
      }
    },
    deactivated(){
      if(this.autoplay){
        this.swiper.stopAutoplay()
      }
   },
    methods: {
      initSwiper() {
          this.swiper = new Swiper('.swiper-container', {
            initialSlide :this.initialSlide,
            prevButton: this.btn ? '.swiper-button-prev' : '',
            nextButton: this.btn ? '.swiper-button-next' : '',
            autoplayDisableOnInteraction: false,
            autoplay: this.autoplay ? 5000 : false,
            onSlideChangeStart: (swiper) => {
              this.$emit('scroll_index', swiper.activeIndex)
            },
            // 如果需要分页器
            pagination: this.isdos ? '.swiper-pagination' : false,
          })
        if(this.swiper.length){
          this.swiper=this.swiper[this.swiper.length-1]
        }
      }
    },
    watch: {
      active_index(newIndex) {
        if(this.active_index){
          console.log(newIndex)
          this.swiper.slideTo(newIndex)
        }
      }
    }
  }
</script>


<style scoped lang="scss">
  img {
    height: 100%;
  }

  .swiper-container {
    height: 100%;
  }

</style>
